﻿using DevelopTool.Bll.DbBlls;
using DevelopTool.Common;
using DevelopTool.Forms.BaseForms;
using DevelopTool.Forms.DbForms.ExecuteForms;
using DevelopTool.Forms.LodingForm;
using DevelopTool.Model;
using DevelopTool.Model.DbModels;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.Data;

namespace DevelopTool.Forms.DbForms.SourceForms
{
    /// <summary>
    /// Oracle资源信息窗体
    /// </summary>
    public partial class OracleSourceForm : BaseUIPage
    {

        /// <summary>
        /// 连接信息
        /// </summary>
        private DbInfo dbInfo;

        /// <summary>
        /// Oracle操作类
        /// </summary>
        private OracleDbBll oracleDbBll;


        /// <summary>
        /// DataGridView列信息集合
        /// </summary>
        private List<DataGridColumn> dataGridColumns = new List<DataGridColumn>()
              {
                    { new DataGridColumn("SOURCE_NAME"){ColumnText="资源名称",Width=0,ColumnType = ColumnType.DefaultFilter | ColumnType.RowMain}},
                    { new DataGridColumn("ROW_COUNT"){ColumnText="数据行数",Width=-1}},
                    { new DataGridColumn("COMMENTS"){ColumnText="注释",Width=0,ColumnType=ColumnType.DefaultFilter|ColumnType.LongText,ShowFormProperty=new ShowFormProperty(){
                BaseNameColumn="SOURCE_NAME",ShowTextLength=20,TextType="Text"
                }}},
                    { new DataGridColumn("OWNER"){ColumnText="实例",Width=100}},
                    { new DataGridColumn("TEXT_LENGTH"){ColumnText="文本长度",Width=-1}},
                    { new DataGridColumn("TEXT"){ColumnText="Sql文本",Width=0,ColumnType=ColumnType.LongText,ShowFormProperty=new ShowFormProperty(){
                BaseNameColumn="SOURCE_NAME"
                }}}
              };

        public OracleSourceForm(DbInfo dbInfo)
        {
            InitializeComponent();
            this.dbInfo = dbInfo.CloneObj();

        }

        private void OracleSourceInfoForm_Load(object sender,EventArgs e)
        {
            this.Disposed += this.OracleSourceForm_Disposed;

            oracleDbBll = new OracleDbBll(dbInfo);

            InitDate();

            this.dataDisplayControl.DbInfo = this.dbInfo;

            this.dataDisplayControl.BindContextMenuStrip(this.ContextMenuStripDgv);//绑定右键菜单
        }



        private void InitDate()
        {
            DataTable dataTable = new DataTable();
            LoadingHelper.ShowLoading("获取资源数据",() =>
           {
               //查询指定数据库表信息
               dataTable = oracleDbBll.GetSources();
           });

            this.dataDisplayControl.BindData(dataTable,this.dataGridColumns,"ROW_COUNT DESC");

            this.backgroundWorker.RunWorkerAsync(dataTable);//启动后台任务，获取行数
        }


        private void 查询资源数据ToolStripMenuItem_Click(object sender,EventArgs e)
        {
            UITabControl parentTabControl = this.GetParentControl<UITabControl>();
            if(parentTabControl != null)
            {
                string sourceName = this.dataDisplayControl.SelectedRowDic["SOURCE_NAME"];
                string sql = $"select * from {sourceName} where 1=1";
                TabControlHelper.AddPageToTabControl(parentTabControl,new ExecuteSqlForm(dbInfo,sql),$"{dbInfo.NodeName}-查询",true,$"{sourceName}-ExecuteSqlForm");
            }
        }


        private void dataDisplayControl_DataReLoad(object sender,EventArgs e)
        {
            InitDate();
        }
        #region 后台任务

        /// <summary>
        /// 后台任务-执行
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void backgroundWorker_DoWork(object sender,System.ComponentModel.DoWorkEventArgs e)
        {
            if(!(e.Argument is DataTable dataTable) || dataTable.Rows.Count == 0) return;

            //显示进度条
            this.Invoke(new Action(() =>
            {
                this.dataDisplayControl.ProcessBar.Visible = true;
                this.dataDisplayControl.ProcessBar.Maximum = dataTable.Rows.Count;
            }));

            foreach(DataRow dataRow in dataTable.Rows)
            {
                if(this.backgroundWorker.CancellationPending) break;

                string owner = dataRow["OWNER"].ToString();
                string object_name = dataRow["SOURCE_NAME"].ToString();
                SourceText sourceText = null;
                try
                {
                    int rowCount = this.oracleDbBll.GetRowCount($"{owner}.{object_name}");
                    sourceText = new SourceText() { Owner = owner,Object_Name = object_name,Text = "",LineNum = rowCount };
                }
                catch(Exception ex)
                {
                    sourceText = new SourceText() { Owner = owner,Object_Name = object_name,Text = ex.Message,LineNum = -1 };
                }

                backgroundWorker.ReportProgress(0,new Tuple<DataTable,SourceText>(dataTable,sourceText));//报告状态，展示结果
            }
        }


        /// <summary>
        /// 后台任务-报告
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void backgroundWorker_ProgressChanged(object sender,System.ComponentModel.ProgressChangedEventArgs e)
        {
            Tuple<DataTable,SourceText> tuple = e.UserState as Tuple<DataTable,SourceText>;

            //填充脚本信息
            for(int i = 0 ; i < tuple.Item1.Rows.Count ; i++)
            {
                if(tuple.Item1.Rows[i]["OWNER"].ToString() == tuple.Item2.Owner && tuple.Item1.Rows[i]["SOURCE_NAME"].ToString() == tuple.Item2.Object_Name)
                {
                    tuple.Item1.Rows[i]["ROW_COUNT"] = tuple.Item2.LineNum;
                    break;
                }
            }
            this.dataDisplayControl.ProcessBar.Value++;
        }

        /// <summary>
        /// 后台任务-完成
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void backgroundWorker_RunWorkerCompleted(object sender,System.ComponentModel.RunWorkerCompletedEventArgs e)
        {
            if(e.Cancelled) return;

            UINotifierHelper.ShowNotifier("已加载完成所有行数",UINotifierType.OK,"Oracle资源",timeout: 2000);
            this.dataDisplayControl.ProcessBar.Value = 0;
            this.dataDisplayControl.ProcessBar.Visible = false;
        }


        #endregion

        private void OracleSourceForm_Disposed(object sender,EventArgs e)
        {
            try
            {
                this.backgroundWorker.CancelAsync();
                this.backgroundWorker.Dispose();
            }
            catch(Exception ex)
            {
                LogHelper.WriteErrLog(ex);
            }
        }
    }
}
